<template>
  <div class="pagination">
    <h1>{{ startAndEnd }}</h1>
    <button @click="$emit('changeLeft')" :disabled="pageNo == 1">上一页</button>
    <button v-show="startAndEnd.start != 1" @click="handler1(1)">1</button>
    <button v-show="startAndEnd.start > 2">...</button>
    <button v-for="(item, index) in pagerList" :key="index" :class="{ active: pageNo == item }" @click="handler1(item)">{{ item }}</button>
    <button v-show="startAndEnd.end < pageTotal - 1">...</button>
    <button v-show="startAndEnd.end != pageTotal" @click="handler1(pageTotal)">{{ pageTotal }}</button>
    <button @click="$emit('changeRight')" :disabled="pageNo == pageTotal">下一页</button>
    <button style="margin-left: 30px; background-color: red; color: #fff">共{{ total }}条</button>
  </div>
</template>

<script>
export default {
  props: ["total", "pageSize", "pageNo", "pager"],
  name: "Pagination",
  computed: {
    pageTotal() {
      let res = Math.ceil(this.total / this.pageSize);
      return res;
    },
    startAndEnd() {
      let start = 0;
      let end = 0;
      const { pageTotal, pageSize, pageNo, pager } = this;

      if (pageTotal < pager) {
        start = 1;
        end = pageTotal;
      } else {
        start = pageNo - parseInt(pager / 2);
        end = pageNo + parseInt(pager / 2);
        if (start < 1) {
          start = 1;
          end = pager;
        }
        if (end > pageTotal) {
          start = pageTotal - pager + 1;
          end = pageTotal;
        }
      }
      return { start, end };
    },
    pagerList() {
      let arr = [];
      for (let i = this.startAndEnd.start; i <= this.startAndEnd.end; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  methods: {
    handler1(item) {
      if (item == this.pageNo) {
        alert("请不要重复点击");
      } else {
        this.$emit("changePageNo", item);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
